package com.v5ba;

import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.editor.Caret;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import org.jetbrains.annotations.NotNull;

public class ReplaceContentAction extends AnAction {
    @Override
    public void actionPerformed(@NotNull AnActionEvent e) {
        Project project = e.getProject();
        Editor editor = e.getData(CommonDataKeys.EDITOR);
        if (editor != null){
            Caret caret = editor.getCaretModel().getPrimaryCaret();
            int start = caret.getSelectionStart();
            int end = caret.getSelectionEnd();
            Document document = editor.getDocument();
            WriteCommandAction.runWriteCommandAction(project, ()->{
                document.replaceString(start, end, "你被替换了");
            });
            caret.removeSelection();
        }
    }
    @Override
    public void update(@NotNull AnActionEvent e) {
        super.update(e);
        Editor editor = e.getData(CommonDataKeys.EDITOR);
        boolean isEnabled = false;
        if (editor != null){
            isEnabled = true;
        }
        e.getPresentation().setEnabled(isEnabled);
    }
}
